﻿namespace Pottery.ServiceLocator
{
    using System;
    using Pottery.Module.Infrastructure.Interfaces;
    using System.Collections.Generic;
    using Pottery.Module.Store.Contracts;
    using Pottery.Module.Store;

    /// <summary>
    /// Class for Service Locator
    /// </summary>
    public class ServiceLocator : IServiceLocator
    {
        #region Constructors

        private ServiceLocator()
        {
            m_DictionaryOfControllers = new Dictionary<Type, object>();
            ///TODO:HardCode
            m_DictionaryOfControllers.Add(typeof(IUserContract), new UserController(StoreStorage.Instance, this));
        }

        #endregion

        #region Properties

        /// <summary>
        /// Gets instance of service locator
        /// </summary>
        public static ServiceLocator Instance
        {
            get
            {
                lock (__murex)
                {
                    if (m_ServiceLocator == null)
                        m_ServiceLocator = new ServiceLocator();

                    return m_ServiceLocator;
                }
            }
        }

        #endregion

        #region IServiceProvider Implementation

        /// <summary>
        /// Gets object by type
        /// </summary>
        /// <param name="serviceType">Type</param>
        /// <returns>New object</returns>
        public object GetService(Type serviceType)
        {
            if (serviceType == null)
                throw new ArgumentNullException();

            if (!m_DictionaryOfControllers.ContainsKey(serviceType))
                return null;

            return m_DictionaryOfControllers[serviceType];
        }

        /// <summary>
        /// Adds new pair Inerface-Class into dictionary
        /// </summary>
        /// <param name="key">Key type</param>
        /// <param name="value">Value type</param>
        public void Add(Type key, object value)
        {
            if (key == null || value == null)
                throw new ArgumentNullException();

            m_DictionaryOfControllers.Add(key, value);
        }

        /// <summary>
        /// Removes item from dictionary
        /// </summary>
        /// <param name="key">Item key type</param>
        public void Remove(Type key)
        {
            if (key == null)
                throw new ArgumentNullException();

            m_DictionaryOfControllers.Remove(key);
        }

        #endregion

        #region Fields

        private static ServiceLocator m_ServiceLocator = default(ServiceLocator);
        private Dictionary<Type, object> m_DictionaryOfControllers;
        private readonly static object __murex = new object();

        #endregion

    }
}
